/*
 * Copyright (C) 2011 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.ui;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.common.network.ApiAsyncTask.ApiRequestListener;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.ThemeManager;
import com.mol.market.common.util.Utils;
import com.mol.market.common.vo.RecommendTopic;
import com.mol.market.common.widget.AppListAdapter;
import com.mol.market.common.widget.LazyloadListActivity;
import com.mol.market.common.widget.LoadingDrawable;

/**
 * 玩家推荐讨论页
 * 
 * @author andrew.wang
 * @date   2011-9-5
 * @since  Version 0.8
 *
 */
public class RecommendDiscussActivity extends LazyloadListActivity implements ApiRequestListener {

    private RecommendTopic mTopic;
    private int mTotalSize;

    private AppListAdapter mCommentAdapter;
    
    private EditText mComment;
    private Button mSend;
    // Loading
    private FrameLayout mLoading;
    private ProgressBar mProgress;
    private TextView mNoData;
    
    @Override
    public boolean doInitView(Bundle savedInstanceState) {
        
        setContentView(R.layout.market_activity_comment_list);
        
        mTopic = (RecommendTopic) getIntent()
                .getSerializableExtra(Constants.EXTRA_RECOMMEND_DETAIL);
        
        initViews();
        
        lazyload();
        return true;
    }
    
    /* (non-Javadoc)
     * @see android.app.Activity#onResume()
     */
    @Override
    protected void onResume() {
        super.onResume();

    }

    /* (non-Javadoc)
     * @see android.app.Activity#onPause()
     */
    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    public void doLazyload() {
        MarketAPI.getMasterRecommendDiscuss(getApplicationContext(), this, getItemsPerPage(),
                getStartIndex(), mTopic.id);
    }


    @Override
    public AppListAdapter doInitListAdapter() {
        mCommentAdapter = new AppListAdapter(
                getApplicationContext(), 
                null,
                R.layout.market_list_item_comment, 
                new String[] { 
                    Constants.KEY_DISCUSS_AUTHOR,
                    Constants.KEY_COMMENT_DATE, 
                    Constants.KEY_DISCUSS_CONTENT }, 
                new int[] {
                    R.id.tv_author, 
                    R.id.tv_time, 
                    R.id.tv_comment });
        mCommentAdapter.setActivity(this);
        return mCommentAdapter;
    }
    
    /*
     * 初始化View 判断用户是否登录，并显示没有登录的提示信息
     */
    private void initViews() {
        
        RelativeLayout ll = (RelativeLayout) findViewById(R.id.login);
        ll.setOnClickListener(this);
        ll.setBackgroundResource(ThemeManager.getResource(mSession, 
                ThemeManager.KEY_ACTION_BAR_BG));
        TextView info = (TextView) ll.findViewById(R.id.tv_info);
        info.setTextAppearance(getApplicationContext(), ThemeManager.getResource(mSession, 
                ThemeManager.KEY_ACTION_BAR_FONT_M));
        
        mLoading = (FrameLayout) findViewById(R.id.loading);
        mProgress = (ProgressBar) mLoading.findViewById(R.id.progressbar);
        mProgress.setIndeterminateDrawable(new LoadingDrawable(getApplicationContext()));
        mProgress.setVisibility(View.VISIBLE);
        mNoData = (TextView) mLoading.findViewById(R.id.no_data);
        mNoData.setOnClickListener(this);
        
        mList = (ListView) findViewById(android.R.id.list);
        mList.setEmptyView(mLoading);
        
        toogleCommentViewStatus();
    }
    
    /*
     * 切换登录和评论控件的状态
     */
    private void toogleCommentViewStatus() {

        if (mSession.isLogin()) {
            findViewById(R.id.login).setVisibility(View.INVISIBLE);
            LinearLayout ll = (LinearLayout) 
                (((ViewStub) findViewById(R.id.view_stub_product_comment)).inflate());
            ll.setBackgroundResource(ThemeManager.getResource(mSession,
                    ThemeManager.KEY_ACTION_BAR_BG));
            Button send = (Button) ll.findViewById(R.id.ib_send);
            send.setTextAppearance(getApplicationContext(),
                    ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_FONT_M));
            mComment = (EditText) findViewById(R.id.et_comment);
            mSend = (Button) findViewById(R.id.ib_send);
            mSend.setOnClickListener(this);
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        toogleCommentViewStatus();
        super.onActivityResult(requestCode, resultCode, data);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onSuccess(int method, Object obj) {
        if (method == MarketAPI.ACTION_GET_DISCUSS) {
            HashMap<String, Object> result = (HashMap<String, Object>) obj;

            mTotalSize = (Integer) result.get(Constants.KEY_TOTAL_SIZE);

            if (mTotalSize > 0) {
                // 成功获取评论列表
                mCommentAdapter.addDataList((ArrayList<HashMap<String, Object>>) result
                        .get(Constants.KEY_COMMENT_LIST));
            } else {
                // 暂无评论
                HashMap<String, Object> noData = new HashMap<String, Object>();
                noData.put(Constants.KEY_DISCUSS_CONTENT, getString(R.string.hint_no_comments));
                mCommentAdapter.addData(noData);
            }
            setLoadResult(true);
        } else if(method == MarketAPI.ACTION_ADD_DISCUSS) {
            mSend.setEnabled(true);
            addMyComment();
            mComment.setText("");
            Utils.makeEventToast(getApplicationContext(), (String) obj, false);
        }
    }

    @Override
    public void onError(int method, int statusCode) {
        
        if (method == MarketAPI.ACTION_ADD_DISCUSS) {
            mSend.setEnabled(true);
            handlePostError(statusCode);
        } else if (method == MarketAPI.ACTION_GET_DISCUSS) {
            // 超时
            mNoData.setVisibility(View.VISIBLE);
            mProgress.setVisibility(View.GONE);
            setLoadResult(false);
        }
    }
    
    @Override
    protected int getItemCount() {
        return mTotalSize;
    }
    
    /*
     * 处理评论的异常信息
     */
    private void handlePostError(int statusCode) {
        switch (statusCode) {
        case 232:
            // 非法回复内容
            Utils.makeEventToast(getApplicationContext(), getString(R.string.alert_unsafe_word),
                    false);
            break;
        case 225:
            // 没有对应的帖子
            Utils.makeEventToast(getApplicationContext(),
                    getString(R.string.alert_product_not_exist), false);
            break;
        case 233:
            // 帐号被禁言
            Utils.makeEventToast(getApplicationContext(), getString(R.string.alert_user_forbidden),
                    false);
            break;
        default:
            // 网络问题
            Utils.makeEventToast(getApplicationContext(), getString(R.string.alert_post_error),
                    false);
            break;
        }
    }
    
    
    @Override
    public void onClick(View v) {
        
        super.onClick(v);
        
        switch (v.getId()) {
        case R.id.login:
            // 登录
            Intent loginIntent = new Intent(getApplicationContext(), LoginActivity.class);
            startActivityForResult(loginIntent, 0);
            break;
            
        case R.id.ib_send:
            // 发送评论
            String body = mComment.getText().toString();
            if (TextUtils.isEmpty(body)) {
                // 不能发表空内容
                Utils.makeEventToast(getApplicationContext(),
                        getString(R.string.alert_post_not_null), false);
            } else {
                mSend.setEnabled(false);
                MarketAPI.addMasterRecommendDiscuss(getApplicationContext(),
                        RecommendDiscussActivity.this, mTopic.id,
                        body.trim());
            }
            break;
            
        case R.id.no_data:
            // 重试
            mProgress.setVisibility(View.VISIBLE);
            mNoData.setVisibility(View.GONE);
            lazyload();
            break;

        default:
            break;
        }
    }
    
    /*
     * 显示我的评论信息
     */
    private void addMyComment() {
        String commentBody = mComment.getText().toString();
        HashMap<String, Object> comment = new HashMap<String, Object>();
        comment.put(Constants.KEY_DISCUSS_CONTENT, commentBody);
        comment.put(Constants.KEY_DISCUSS_AUTHOR, mSession.getUserName());
        comment.put(Constants.KEY_COMMENT_DATE, Utils.formatTime(System.currentTimeMillis()));

        if (mTotalSize <= 0) {
            // 第一条评论
            mCommentAdapter.clearData();
        }
        mCommentAdapter.insertData(comment);
    }

}
